package evolutionaryballoons.behavior.genetic;

import java.util.Random;

public class Programmer {
	private Random random;
	
	public Programmer() {
		random = new Random();
	}
	
	private Node generateNode(int allowedDecisionNodes) {
		int r = (allowedDecisionNodes > 0) ? random.nextInt(3) : 0;
		
		switch(r) {
			case 0:
				ActionNode anode = new ActionNode();
				anode.action = Actions.values()[random.nextInt(Actions.values().length)];
				
				return anode;
			
			case 1:
				DecisionNode dnode = new DecisionNode();
				dnode.limit = random.nextFloat() * 2.0f - 1.0f;
				dnode.source = Sources.values()[random.nextInt(Sources.values().length)];
				dnode.leftNode = generateNode(allowedDecisionNodes--);
				dnode.rightNode = generateNode(allowedDecisionNodes--);
				
				return dnode;
				
			case 2:
				MultipleNode mnode = new MultipleNode();
				mnode.leftNode = generateNode(allowedDecisionNodes--);
				mnode.rightNode = generateNode(allowedDecisionNodes--);
				
				return mnode;
		}
		
		return null;
	}
	
	public Node buildRandomTree(int allowedDecisionNodes) {
		Node node = generateNode(allowedDecisionNodes);
		
		return node;
	}

	public static void log(Node node, int indent) {
		String ind = "";
		
		for (int i = 0; i < indent; i++) {
			ind += "|";
		}
		
		ind += "-";
		
		if (node instanceof DecisionNode) {
			DecisionNode d = (DecisionNode) node;
			String output = String.format("DecisionNode - %s < %s?", d.source.toString(), d.limit);
			System.out.println(ind + output);
			
			log(d.leftNode, indent + 1);
			log(d.rightNode, indent + 1);
			
			return;
		}
		
		if (node instanceof MultipleNode) {
			System.out.println(ind + "MultipleNode");
			
			MultipleNode m = (MultipleNode) node;
			log(m.leftNode, indent + 1);
			log(m.rightNode, indent + 1);
			
			return;
		}
		
		if (node instanceof ActionNode) {
			ActionNode b = (ActionNode) node;
			System.out.println(ind + "# " + b.action.toString());
			
			return;
		}
	}
}
